const mongoose = require('mongoose');
const Router = require('koa-router')

const AddressRouter = new Router();

AddressRouter.post('/add', async (ctx) => {
  try {
    const AddressSchema = mongoose.model('Address');
    const newAddress = new AddressSchema(ctx.request.body);
    await newAddress.save(ctx.request.body);
    ctx.body = {
      code: 200,
      message: '新增成功',
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '新增失败',
    }
  }
})

// 修改地址信息
AddressRouter.put('/edit', async (ctx) => {
  try {
    const AddressSchema = mongoose.model('Address');
    const { addressId, ...rest } = ctx.request.body;
    await AddressSchema.updateOne({_id: addressId}, {$set: rest})
    ctx.body = {
      code: 200,
      message: '修改成功',
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '修改失败',
    }
  }
})

AddressRouter.get('/get', async (ctx) => {
  try {
    const AddressSchema = mongoose.model('Address');
    const addressList = await AddressSchema.find().exec();
    ctx.body = {
      code: 200,
      message: addressList,
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: err,
    }
  }
})

AddressRouter.delete('/delete', async (ctx) => {
  try {
    const AddressSchema = mongoose.model('Address');
    const { addressId } = ctx.request.query;
    await AddressSchema.remove({_id: addressId});
    ctx.body = {
      code: 200,
      message: '删除成功',
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '删除失败',
    }
  }
})

// 获取单个地址的信息
AddressRouter.get('/getAddressInfo', async (ctx) => {
  try {
    const AddressSchema = mongoose.model('Address');
    const { addressId } = ctx.request.query;
    const res = await AddressSchema.findOne({_id: addressId}).exec();
    ctx.body = {
      code: 200,
      message: res,
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: err,
    }
  }
})


module.exports = AddressRouter;